package com.zwh.autoconfigure.eventbus;

import java.util.List;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;


/**
 * @author monkey
 * @date 2020/11/4 11:34
 **/
@Component
public class EventBusCenter {// implements InitializingBean, DisposableBean {

    // 管理同步事件
    private EventBus syncEventBus = new EventBus();

    // 管理异步事件
    private AsyncEventBus asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());

    public void postSync(Object event) {
        syncEventBus.post(event);
    }

    public void postAsync(Object event) {
        asyncEventBus.post(event);
    }

    /**
     * 注册事件监听器
     * @param listeners
     */
    public void registry(List<Object> listeners){
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct调用");
    }
    /*@PostConstruct
    public void init() {

        // 获取所有带有 @EventBusListener 的 bean，将他们注册为监听者
        Map<String, Object> beansWithAnnotation = SpringContextUtils.getApplicationContext().getBeansWithAnnotation(EventBusListener.class);
        List<Object> listeners = beansWithAnnotation.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
    }*/

//    @Override
//    public void destroy() throws Exception {
//
//    }

    /*@Override
    public Object postProcessAfterInitialization(Object bean, String beanName){
        // 获取所有带有 @EventBusListener 的 bean，将他们注册为监听者
        Map<String, Object> beansWithAnnotation = SpringContextUtils.getApplicationContext().getBeansWithAnnotation(EventBusListener.class);
        List<Object> listeners = beansWithAnnotation.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
        return bean;
    }*/
    /*@Override
    public void afterPropertiesSet() throws Exception {
// 获取所有带有 @EventBusListener 的 bean，将他们注册为监听者
        Map<String, Object> beansWithAnnotation = SpringContextUtils.getApplicationContext().getBeansWithAnnotation(EventBusListener.class);
        List<Object> listeners = beansWithAnnotation.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
        for (Object listener : listeners) {
            asyncEventBus.register(listener);
            syncEventBus.register(listener);
        }
    }*/

}
